package top.yrlby.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import top.yrlby.common.BaseContext;
import top.yrlby.common.R;
import top.yrlby.pojo.Employee;
import top.yrlby.service.EmployeeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author baiyang
 * @since 2022-09-05
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 后台登录
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    public  R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        //接受前台发送过来的密码并进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //构建查询条件
        //.eq等同于SQL语句中的where条件语句
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());

        //调用mybatisPlus自动创建service层实现SQL语句
        //getOne: MyBatisPlus提供
        Employee emp = employeeService.getOne(wrapper);
        //判断登录密码是否为空
        if(emp == null){
            return R.error("登录失败");
        }

        //判断登录密码是否正确
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //判断该账号是否被管理员禁用
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //把登录人的id存入session中
        request.getSession().setAttribute("employee",emp.getId());
        Long empId = (Long) request.getSession().getAttribute("employee");
        //存储到当前线程的ThreadLocal中，可以往后边继续传递
        BaseContext.setCurrentId(empId);
        return R.success(emp);
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        //清理Session中保存的当前登录员工的id
        //session.removeAttribute("employee");

        //销毁session
        session.invalidate();
        return R.success("退出成功");
    }

    /**
     * 新增员工信息
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpServletRequest request){
        log.info("新增员工，员工信息：{}",employee.toString());

        //设置默认密码为123456并进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        //设置默认时间
//        //LocalDateTime 为 年-月-日 时:分:秒
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //获取当前登录人的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        //save: MyBatisPlus提供
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 条件分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页构造器
        Page<Employee> employeePage = new Page<>(page,pageSize);

        //构建查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件: lik '%xxx%'
        //StringUtils.isNotBlank(name): 会对name进行trim()操作让后判断是否为null和判断是否为空字符串
        queryWrapper.like(StringUtils.isNotBlank(name),Employee::getName,name);

        //添加排序条件: desc(倒序） order by 字段名 desc;
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //调用mybatisPlus自动创建service层实现SQL语句
        //page: MyBatisPlus提供
        employeeService.page(employeePage,queryWrapper);

        // 底层会通过如下的set方法，把查询出来的数据放置到pageInfo对象中
        // pageInfo.setRecords(list);
        //返回前台数据
        return R.success(employeePage);
    }

    /**
     * 禁用/启用员工账号
     * @param employee
     * @param request
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request){
        log.info(employee.toString());
//        //获取修改信息人的参数和禁用/启用的参数
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);
//        employee.setUpdateTime(LocalDateTime.now());
        //调用mybatisPlus自动创建service层实现SQL语句
        //updateById: MyBatisPlus提供
        employeeService.updateById(employee);
        //返回前台数据
        return R.success("修改成功！");
    }


    /**
     * 修改前查询修改信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息");
        Employee employee = employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("对不起，没有查询到当前员工信息！");

    }
}

